"""Migrate message to orm

Revision ID: 95badb46fdf9
Revises: 3c683a662c82
Create Date: 2024-12-05 14:02:04.163150

"""

from typing import Sequence, Union

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "95badb46fdf9"
down_revision: Union[str, None] = "08b2f8225812"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("messages", sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True))
    op.add_column("messages", sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False))
    op.add_column("messages", sa.Column("_created_by_id", sa.String(), nullable=True))
    op.add_column("messages", sa.Column("_last_updated_by_id", sa.String(), nullable=True))
    op.add_column("messages", sa.Column("organization_id", sa.String(), nullable=True))
    # Populate `organization_id` based on `user_id`
    # Use a raw SQL query to update the organization_id
    op.execute(
        """
        UPDATE messages
        SET organization_id = users.organization_id
        FROM users
        WHERE messages.user_id = users.id
    """
    )
    op.alter_column("messages", "organization_id", nullable=False)
    op.alter_column("messages", "tool_calls", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False)
    op.alter_column("messages", "created_at", existing_type=postgresql.TIMESTAMP(timezone=True), nullable=False)
    op.drop_index("message_idx_user", table_name="messages")
    op.create_foreign_key(None, "messages", "agents", ["agent_id"], ["id"])
    op.create_foreign_key(None, "messages", "organizations", ["organization_id"], ["id"])
    op.drop_column("messages", "user_id")
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column("messages", sa.Column("user_id", sa.VARCHAR(), autoincrement=False, nullable=False))
    op.drop_constraint(None, "messages", type_="foreignkey")
    op.drop_constraint(None, "messages", type_="foreignkey")
    op.create_index("message_idx_user", "messages", ["user_id", "agent_id"], unique=False)
    op.alter_column("messages", "created_at", existing_type=postgresql.TIMESTAMP(timezone=True), nullable=True)
    op.alter_column("messages", "tool_calls", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=True)
    op.drop_column("messages", "organization_id")
    op.drop_column("messages", "_last_updated_by_id")
    op.drop_column("messages", "_created_by_id")
    op.drop_column("messages", "is_deleted")
    op.drop_column("messages", "updated_at")
    # ### end Alembic commands ###
